<?php

namespace liketp;

use liketp\console\CommandRequest;

/**
 * 控制台应用管理类
 * 负责处理通过命令行输入的指令
 */
class Console
{
    protected $app;
    protected $defaultNamespace = 'liketp\console\command\\';
    protected $defaultMethod = 'exec';
    protected $routes = [];
    protected $alias = [
        'go' => 'serve',
        'run' => 'serve',
    ];

    public function __construct(App $app)
    {
        $this->app = $app;
    }

    public function run(array $argv)
    {
        $this->init($argv);
        $this->dispatch($this->app->request);
    }


    //------------------------------------------------ protected
    protected function init($argv)
    {
        $this->app->initialized() || $this->app->initialize();
        $this->app->bind('request', CommandRequest::class);
        $this->app->request->setArgv($argv);
    }

    protected function dispatch($request)
    {
        $cmd = $request->command();
        [$class, $method] = $this->routeTarget($cmd);
        $this->app->invokeCommand($class, $method);
    }

    protected function routeTarget(string $cmd)
    {
        $cmd = $this->alias[$cmd] ?? $cmd;
        $cmd = $this->routes[$cmd] ?? $cmd;
        if (strpos($cmd, '\\') === false) {
            $cmd = $this->defaultNamespace . str_to_camel($cmd, true);
        }

        $items = explode('@', $cmd) + ['', $this->defaultMethod];

        return $items;
    }
}
